package com.common.util.picture;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import sun.misc.BASE64Decoder;  


public class PictureBase64 { 
	
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder(); 
    
    public static String dataimg = "\\<img[^>]*src=\"data:image/[^>]*>";
    public static String datasrc = "data:image[^>]*\" ";
    public static String datasuffix = "data:image[^>]*;base64,";
    
    /**
     * base64的图片保存到本地
     * @param base64ImgData base64数据
     * @param filePath 保存路径
     * @throws IOException 异常
     */
	public static void convertBase64DataToImage(String base64ImgData,String filePath) throws IOException {
		//System.out.println("filePath:"+filePath);
		BASE64Decoder d = new BASE64Decoder();
		byte[] bs = d.decodeBuffer(base64ImgData);
		FileOutputStream os = new FileOutputStream(filePath);
		os.write(bs);
		os.close();
	}
	/**
	 * 获取纯文本
	 * @param htmlStr html内容
	 * @return 纯文本
	 */
	public static String removeHtmlInTag(String htmlStr) {
		  Document doc = Jsoup.parse(htmlStr);
		  String text = doc.text();
		  StringBuilder builder = new StringBuilder(text);
		  int index = 0;
		  while(builder.length()>index){
		    char tmp = builder.charAt(index);
		    if(Character.isSpaceChar(tmp) || Character.isWhitespace(tmp)){
		      builder.setCharAt(index, ' ');
		    }
		    index++;
		  }
		  text = builder.toString().replaceAll(" +", " ").trim();
		  return text;
	}
	
	/**
	 * 把html代码的base64图片保存到磁盘并且返回正确url
	 * @param shtml html代码
	 * @param basePath
	 * @param reSavePath
	 * @param projectName项目名
	 * @return 正确替换url的html文本
	 */
	public static String getShtmlContent(String shtml,String basePath,String reSavePath,String projectName){
		
		File reSavePathfile=new File(reSavePath);
		if(!reSavePathfile.exists()){
			reSavePathfile.mkdir();
		}
		File basePathfile=new File(reSavePath+File.separator+basePath);
		if(!basePathfile.exists()){
			basePathfile.mkdir();
		}
		
    	String htmlContent = shtml;
    	Pattern pattern = Pattern.compile(dataimg);
		Matcher matcher = pattern.matcher(shtml);
		while(matcher.find()){		//找出base64图片元素	
			try {
				String img = matcher.group();
				String src = getOneDataString(img,datasrc);
				String suffix = getOneDataString(src,datasuffix);
				String base64img = src.replace(suffix, "");
				String relSuffix = getRelSuffix(suffix);
				String path = getPathFileName(basePath,relSuffix);
				htmlContent = htmlContent.replace(src, projectName + File.separator + path+"\"");
				convertBase64DataToImage(base64img,reSavePath + File.separator + path);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return htmlContent;
	}
	
	/**
	 * 单图片base64上传
	 * @param src 带格式类型的base64String
	 * @param basePath 某文件夹
	 * @param reSavePath 服务器路径
	 * @return src的url
	 */
	public static String getImgUrl(String src,String basePath,String reSavePath,String projectName){
		String path = "";
		try {
			String suffix = getOneDataString(src,datasuffix);
			String base64img = src.replace(suffix, "");
			String relSuffix = getRelSuffix(suffix);
			path = getPathFileName(basePath,relSuffix);
			File reSavePathfile=new File(reSavePath);
			if(!reSavePathfile.exists()){
				reSavePathfile.mkdir();
			}
			File basePathfile=new File(reSavePath+File.separator+basePath);
			if(!basePathfile.exists()){
				basePathfile.mkdir();
			}
			convertBase64DataToImage(base64img,reSavePath + File.separator + path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return projectName + File.separator + path;
	}
	
	/**
	 * 生成Src
	 * @param basePath 某文件夹
	 * @param relSuffix 后缀 .xx
	 * @return
	 */
	private static String getPathFileName(String basePath,String relSuffix){
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String fileName = uuid + relSuffix;
		String path = basePath + File.separator+ fileName;
		while(true){
			File file=new File(path);
			if(!file.exists()){
				return path;
			}
			uuid = UUID.randomUUID().toString().replace("-", "");
			fileName = uuid + relSuffix;
			path = basePath + fileName;
		}
	}
	
	/**
	 * 获取符合正则的数据
	 * @param data String数据
	 * @param patternStr 正则规则
	 * @return 符合正则的String数据
	 */
	private static String getOneDataString(String data,String patternStr){
		Pattern pattern = Pattern.compile(patternStr);
		Matcher matcher = pattern.matcher(data);
		String str = null;
		while(matcher.find()){
			str = matcher.group();
		}
		return str;
	}
	
	/**
	 * 根据base64类型获取格式
	 * @param suffix base64类型
	 * @return 格式 .xx
	 */
	private static String getRelSuffix(String suffix){ 
	    switch (suffix) {
		case "data:image/png;base64,":
			return ".png";
		case "data:image/jpeg;base64,":
			return ".jpg";
		case "data:image/gif;base64,":
			return ".gif";
		case "data:image/bmp;base64,":
			return ".bmp";
		case "data:image/x-icon;base64,":
			return ".icon";
		default:
			return suffix.replace("data:image/", ".").replace(";base64,", "");
		}
	} 
}